package com.cdream.basic.spring.aop;

import com.google.common.util.concurrent.RateLimiter;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 限流 AOP
 *
 * @author cdream
 */
@Aspect
@Component
public class LimitAspect {

	//全局限流大小
	private static final RateLimiter rateLimiter = RateLimiter.create(500);


	//Service层切点  限流
	@Pointcut("@annotation(com.cdream.basic.spring.aop.RateLimit)")
	public void ServiceAspect() {

	}

	@Around("ServiceAspect()")
	public Object around(ProceedingJoinPoint joinPoint) {
		// MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		// Method method = signature.getMethod();
		// RateLimit limitAnnotation = method.getAnnotation(RateLimit.class);
		try {
			boolean flag = rateLimiter.tryAcquire();
			if (flag) {
				return joinPoint.proceed();
			} else {
				throw new RuntimeException("请求失败");
			}
		} catch (Throwable e) {
			throw new RuntimeException("请求失败");
		}
	}
}
